﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Snowdreamist.ComponentModel;
using Snowdreamist.Diagnostics;
using Snowdreamist.Runtime;

namespace Snowdreamist.Web.Page
{
    public abstract class PageCollectionBase : PageBase, IPageCollection
    {
        public PageCollectionBase(PageParserBase parser, Uri address)
            : base(parser, address)
        {
            this.Pages = new ReadOnlyCollection<IPagingPage>(this._pages);
        }

        public abstract bool IsPaging { get; }

        public abstract int PageNo { get; }

        public ReadOnlyCollection<IPagingPage> Pages { get; private set; }

        public virtual void RefreshAllPages()
        {
            this.Refreshed += new EventHandler<RefreshedEventArgs>(OnRefreshAllPagesRefreshed);
            this.Refresh();
        }

        public virtual void RefreshAllPagesAsync()
        {
            this.Refreshed += new EventHandler<RefreshedEventArgs>(OnRefreshAllPagesRefreshed);
            this.RefreshAsync();
        }

        public event EventHandler<PageCountChangedEventArgs> PageCountChanged;

        #region protected

        protected readonly List<IPagingPage> _pages = new List<IPagingPage>();

        protected virtual void OnRefreshAllPagesRefreshed(object sender, RefreshedEventArgs e)
        {
            if (e.Error == null)
            {
                this.Refreshed -= new EventHandler<RefreshedEventArgs>(OnRefreshAllPagesRefreshed);
                this.RefreshAllPagesCore();
            }
            else
            {
                SystemRuntime.Current.Log.Write(TraceEventType.Error, (int)EventID.PageParserRefreshFailed, "Fail to refresh all pages for " + this.Identity);
            }
        }

        protected virtual void RefreshAllPagesCore()
        {
            foreach (var page in this.Pages)
                page.RefreshAsync();
        }

        protected virtual void OnPageCountChanged(int oldCount, int newCount)
        {
            if (this.PageCountChanged != null)
                this.PageCountChanged(this, new PageCountChangedEventArgs(oldCount, newCount));
        }

        #endregion protected

        #region private

        #endregion private
    }
}